package com.dennytech.tac.ui.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dennytech.tac.base.CFActivity;
import com.dennytech.tac.model.Attraction;
import com.dennytech.tac.model.Togo;
import com.dennytech.tac.net.api.AttractionInfoApi;
import com.dennytech.tac.statistics.Stat;
import com.dennytech.tac.utils.CFSpannableString;
import com.dennytech.tac.utils.CFUtils;
import com.dennytech.tac.utils.Daemon;
import com.dennytech.tac.utils.db.TogoDBHelper;
import com.dennytech.tac.widget.NetworkImageView;
import com.google.android.photostream.UserTask;
import com.dennytech.tac.R;

public class AttractionInfoActivity extends CFActivity implements
		OnClickListener {

	private Attraction ta;
	private Togo tg;
	private int aid;

	private TextView titleTv;
	private TextView openTv;
	private NetworkImageView headImg;
	private TextView detailTv;
	private LinearLayout contentLay;

	private TextView addPlan;

	private boolean addedToTogo;

	private Task task;

	private Handler handler = new Handler(Daemon.looper()) {
		public void handleMessage(android.os.Message msg) {
			TogoDBHelper helper = TogoDBHelper.instance();

			switch (msg.what) {
			case 0: // check goto db
				tg = helper.query(String.valueOf(aid));
				if (tg != null) {
					addedToTogo = true;
					addPlan.setCompoundDrawables(CFUtils.getDrawable(
							AttractionInfoActivity.this, R.drawable.favorite),
							null, null, null);
					
				} else {
					addedToTogo = false;
					addPlan.setCompoundDrawables(CFUtils.getDrawable(
							AttractionInfoActivity.this,
							R.drawable.favorite_gray), null, null, null);
					
				}
				addPlan.setEnabled(true);
				break;

			default:
				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle b) {
		super.onCreate(b);

		handler.sendEmptyMessage(0);
	}

	@Override
	protected void onDestroy() {
		if (task != null) {
			task.cancel(true);
		}
		super.onDestroy();
	}

	@Override
	protected void initView() {
		setContentView(R.layout.tourist_attraction_info);

		// ta = getIntent().getParcelableExtra("ta");
		aid = getIntent().getIntExtra("id", 0);

		titleTv = (TextView) findViewById(R.id.title);
		openTv = (TextView) findViewById(R.id.open);
		addPlan = (TextView) findViewById(R.id.add_plan);
		addPlan.setOnClickListener(this);
		headImg = (NetworkImageView) findViewById(R.id.head_img);
		headImg.setOnClickListener(this);
		detailTv = (TextView) findViewById(R.id.detail_txt);
		detailTv.setMovementMethod(LinkMovementMethod.getInstance());
		contentLay = (LinearLayout) findViewById(R.id.content_lay);

		contentLay.setVisibility(View.INVISIBLE);
		showProgressDialog("Loading Data...", new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				finish();
			}
		});
		if (task != null) {
			task.cancel(true);
		}
		task = new Task();
		task.execute(aid);
	}

	private void setupView() {
		if (ta != null) {
			titleTv.setText(ta.getName());
			openTv.setText(ta.getOpentime());
			headImg.setImage(ta.getPhotoUrl());
			detailTv.setText(new CFSpannableString(ta.getDetail()).string());
			initMenu();
			contentLay.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.add_plan) {
			TogoDBHelper helper = TogoDBHelper.instance();
			if (addedToTogo) {
				helper.delete(ta.getId());

				addedToTogo = false;
				addPlan.setCompoundDrawables(CFUtils.getDrawable(
						AttractionInfoActivity.this, R.drawable.favorite_gray),
						null, null, null);
				
				Stat.event("attractioninfo", "attractioninfo_addtrip", "remove", 0);
				
			} else {
				tg = new Togo();
				tg.setAttId(ta.getId());
				tg.setStatus(0);
				helper.insert(tg);

				addedToTogo = true;
				addPlan.setCompoundDrawables(CFUtils.getDrawable(
						AttractionInfoActivity.this, R.drawable.favorite),
						null, null, null);
				
				Stat.event("attractioninfo", "attractioninfo_addtrip", "add", 0);
				
			}
			sendBroadcast(new Intent("com.dennytech.tac.action.TOGOLIST_CHANGED"));
		} else if (v.getId() == R.id.head_img) {
			Stat.event("attractioninfo", "attractioninfo_img_click", null, 0);
		}

	}

	private void initMenu() {
		List<Menu> menuList = new ArrayList<Menu>();
		if (!TextUtils.isEmpty(ta.getAddress())) {
			Menu menu = new Menu(R.drawable.ic_address_big, ta.getAddress(),
					null);
			if (ta.getLatitude() != 0 && ta.getLongitude() != 0) {
				menu.intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:"
						+ ta.getLatitude() + "," + ta.getLongitude() + "?q="
						+ ta.getName()));
			}
			menuList.add(menu);
		}
		if (!TextUtils.isEmpty(ta.getTel())) {
			menuList.add(new Menu(R.drawable.ic_phone_big, ta.getTel(),
					new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
							+ ta.getTel()))));
		}

		for (final Menu menu : menuList) {
			View view = getLayoutInflater().inflate(R.layout.menu_item,
					contentLay, false);
			View sep = getLayoutInflater().inflate(R.layout.seperate,
					contentLay, false);
			((ImageView) (view.findViewById(R.id.icon)))
					.setImageResource(menu.icon);
			((TextView) (view.findViewById(R.id.title))).setText(menu.name);
			if (menu.intent != null) {
				view.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						try {
							startActivity(menu.intent);
						} catch (Exception e) {
						}
					}
				});
			}
			contentLay.addView(view);
			contentLay.addView(sep);
		}
	}

	class Menu {
		int icon;
		String name;
		Intent intent;

		public Menu(int ic, String n, Intent i) {
			icon = ic;
			name = n;
			intent = i;
		}
	}

	class Task extends UserTask<Integer, Void, JSONObject> {

		AttractionInfoApi api;

		public Task() {
			api = new AttractionInfoApi();
		}

		@Override
		public JSONObject doInBackground(Integer... params) {
			api.setID(params[0]);
			return api.query();
		}

		@Override
		public void onPostExecute(JSONObject result) {
			if (result != null) {
				ta = Attraction.decode(result);
				setupView();
				dismissDialog();
			} else {
				// set error
				Toast.makeText(AttractionInfoActivity.this, api.errorMsg(),
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}

	}

}
